﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.IO;
using System.Resources;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using EnvDTE;
using Kugar.Core.Collections;
using Kugar.ERPFramework.Entity;
using Kugar.UI.WinForm;
using EnvDTE;
using EnvDTE100;
using Kugar.Core.ExtMethod.Serialization;

namespace Kugar.ERPFramework.View.WinForm
{


    public class RMSEditorControlDesigner : ComponentDesigner
    {
        private DesignerActionListCollection _actionList = null;

        public override void Initialize(IComponent component)
        {
            base.Initialize(component);

            //_actionList = base.ActionLists;

            //if (_actionList == null)
            //{
                _actionList = new DesignerActionListCollection();
            //}

            _actionList.Add(new RMSEditorActionList(this.Component, this));
        }

        public override DesignerActionListCollection ActionLists
        {
            get
            {
                //base.ActionLists.Add(new RMSEditorActionList(this.Component, this));

                //DesignerActionListCollection collection = new DesignerActionListCollection();

                //collection.Add(new RMSEditorActionList(this.Component, this));
                return _actionList;
            }
        }
    }

    public class RMSEditorActionList : DesignerActionList
    {
        private DesignerActionUIService _service;
        private RMSEditorControlDesigner _designer;

        public RMSEditorActionList(IComponent component, RMSEditorControlDesigner designer)
            : base(component)
        {
            this._designer = designer;
            this._service = component.Site.GetService(typeof(DesignerActionUIService)) as DesignerActionUIService;
            this.AutoShow = true;
        }

        public override DesignerActionItemCollection GetSortedActionItems()
        {
            var item = new DesignerActionItemCollection();

            item.Add(new DesignerActionHeaderItem("功能"));

            item.Add(
                    new DesignerActionPropertyItem("RMSList",
                     "权限控制", "功能",
                     "设置关联控件的权限"));

            return item;
        }


        public RMSDesigner SourceControl
        {
            get { return (RMSDesigner)this.Component; }
        }


        [Localizable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Editor(typeof(RMSEditorUITypeDesign), typeof(UITypeEditor))]
        public  IEnumerable<ControlRMSItem> RMSList
        {
            get { return SourceControl.RMSList; }
            set
            {
                //SourceControl.MaxValueControl = value;

                //SourceControl.ControlList.Clear();

                //foreach (var control in value)
                //{
                //    SourceControl.ControlList.Add(control);
                //}

                SourceControl.RMSList = value;

                this._service.Refresh(this.Component);
            }
        }

        public class RMSEditorUITypeDesign : UITypeEditor
        {
            EnvDTE80.DTE2 myDTE;

            public RMSEditorUITypeDesign()
            {
                try
                {
                    
                    //myDTE =new DTEClass();

                    myDTE = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.11.0");

                    if (myDTE==null)
                    {
                        myDTE = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");
                    }

                    //myDTE = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");


                    //if (myDTE == null)
                    //{
                    //    myDTE = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.11.0");

                    //    //myDTE = (EnvDTE.DTE)Microsoft.VisualBasic.Interaction.CreateObject("VisualStudio.DTE.10.0", "");
                    //}
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }


                
            }

            /// <summary>
            /// 获取由 EditValue 方法使用的编辑器样式
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
            {
                if (context != null && context.Instance != null)
                {
                    return UITypeEditorEditStyle.Modal;
                }
                return base.GetEditStyle(context);
            }

            /// <summary>
            /// 使用指定的服务提供程序和上下文编辑指定对象的值。
            /// </summary>
            /// <param name="context">可用于获取附加上下文信息的 ITypeDescriptorContext。</param>
            /// <param name="provider">IServiceProvider，通过它可能获得编辑服务。</param>
            /// <param name="value">正在编辑的值的实例。</param>
            /// <returns>新的对象值。如果该对象的值尚未更改，则这应返回与传递给它的对象相同的对象</returns>
            public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
            {
                //为 UITypeEditor 提供一个接口，用于显示 Windows 窗体，或者在设计模式下在属性网格控件的下拉区域中显示控件。
                IWindowsFormsEditorService iws = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                    

                if (iws != null)
                {

                    var key = ((IDesignerHost) myDTE.ActiveDocument.ActiveWindow.Object).RootComponentClassName;

                    var resFile = Path.Combine(Path.GetDirectoryName(myDTE.ActiveDocument.ProjectItem.ContainingProject.FullName), "RMSList.resx");

                    //MessageBox.Show(str);

                    //var resFile =Path.GetFileNameWithoutExtension(myDTE.ActiveDocument.FullName)+".resx";

                    ControlRMSItem[] rmsItems = null;

                    var srcControl = ((RMSEditorActionList)context.Instance).SourceControl;

                    if (File.Exists(resFile)) 
                    {
                        using (var rr=new ResXResourceReader(resFile) )
                        {
                            foreach (DictionaryEntry  res in rr)
                            {
                                if (res.Key.ToString() == key)
                                {
                                //    var bf = new BinaryFormatter();

                                //    byte[] buf = Convert.FromBase64String(res.Value.ToString());



                                //    using (var ms = new MemoryStream(buf, 0, buf.Length))
                                //    {
                                //        try
                                //        {
                                //            var t = bf.Deserialize(ms);

                                //            rmsItems = (ControlRMSItem[])t;
                                //        }
                                //        catch (Exception ex)
                                //        {
                                //            MessageBox.Show(ex.Message);
                                //            rmsItems = null;
                                //        }


                                //    }

                                    


                                    //MessageBox.Show(res.Value.GetType().ToString());
                                    rmsItems =SerializationExt.XMLToObject<ControlRMSItem[]>(res.Value.ToString());
                                    //MessageBox.Show((rmsItems ==null).ToString());
                                    //rmsItems = (ControlRMSItem[])res.Value;
                                }
                            }

                            rr.Close();
                        }
                        
                    }

                    
                    using (var UIControl = new RMSEditor(srcControl.Form, rmsItems))
                    {
                        if (iws.ShowDialog(UIControl) == DialogResult.OK)
                        {
                            var isNew = !File.Exists(resFile);

                            using (var rw = new ResXResourceWriter(resFile))
                            {

                                var data =SerializationExt.SerializeToXML(UIControl.RMSList.ToArray());
                                rw.AddResource(key, data);
                                rw.Close();
                            }

                            if (isNew)
                            {
                                
                                myDTE.ActiveDocument.ProjectItem.ContainingProject.ProjectItems.AddFromFile(resFile);
                            }

                            MessageBox.Show("保存成功");
                            context.OnComponentChanged();
                        }
                    }
                }
                return value;
            }

            /// <summary>
            /// XML转义字符处理
            /// </summary>
            public static string ConvertXml(string xml)
            {

                xml = (char)1 + xml;   //为了避免首字母为要替换的字符，前加前缀

                for (int intNext = 0; true; )
                {
                    int intIndexOf = xml.IndexOf("&", intNext);
                    intNext = intIndexOf + 1;  //避免&被重复替换
                    if (intIndexOf <= 0)
                    {
                        break;
                    }
                    else
                    {
                        xml = xml.Substring(0, intIndexOf) + "&amp;" + xml.Substring(intIndexOf + 1);
                    }
                }

                for (; true; )
                {
                    int intIndexOf = xml.IndexOf("<");
                    if (intIndexOf <= 0)
                    {
                        break;
                    }
                    else
                    {
                        xml = xml.Substring(0, intIndexOf) + "&lt;" + xml.Substring(intIndexOf + 1);
                    }
                }

                for (; true; )
                {
                    int intIndexOf = xml.IndexOf(">");
                    if (intIndexOf <= 0)
                    {
                        break;
                    }
                    else
                    {
                        xml = xml.Substring(0, intIndexOf) + "&gt;" + xml.Substring(intIndexOf + 1);
                    }
                }

                for (; true; )
                {
                    int intIndexOf = xml.IndexOf("\"");
                    if (intIndexOf <= 0)
                    {
                        break;
                    }
                    else
                    {
                        xml = xml.Substring(0, intIndexOf) + "&quot;" + xml.Substring(intIndexOf + 1);
                    }
                }

                return xml.Replace(((char)1).ToString(), "");

            }
        }
    }
}